//
//  MKImageDownloader.m
//  MKWebImage
//
//  Created by lily on 17/1/1.
//  Copyright © 2017年 lily. All rights reserved.
//

#import "MKImageDownloader.h"

@implementation MKImageDownloader

- (instancetype)initWithUrl:(NSString *)url complete:(void(^)(UIImage *image, NSError *error, MKImageDownloader *loader))complete {
    if (self = [super init]) {
        if (url && [url isKindOfClass:[NSString class]]) {
            NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
            //NSLog(@"img request %@",request);
            // 2.创建请求 并：设置缓存策略为每次都从网络加载 超时时间30秒
//            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5];
            
            __weak typeof(self) weakself = self;
            NSURLSessionTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"end download image...");
                    if (error) {

                        NSLog(@"图片加载失败 %@", error);
                        if (complete) {
                            complete(nil, error, weakself);
                        }
                        return ;
                    }
                    
                    
                    NSError *err = nil;
                    NSData *data = [NSData dataWithContentsOfURL:location options:NSDataReadingMappedAlways error:&err];
                    if (!data || err) {
                        NSLog(@"图片转换失败 %@", err);
                        if (complete) {
                            complete(nil, error, weakself);
                        }
                        return ;
                    }
                    
                    UIImage *image = [[UIImage alloc] initWithData:data];
                    if (image && complete) {
                        complete(image, nil, weakself);
                    }                    
                });
                
            }];
            
            self.task = task;
            
        }
    }
    return self;
}



- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    //[self stopAnimating];
    
    NSLog(@"ERROR : %@",error); //Get informed of the error FIRST
    if([error code] == NSURLErrorCancelled)
        return;
    // 如果是被取消，什么也不干
    if([error code] == NSURLErrorCancelled)  {
        return;
    }
    
    // 后续失败处理
}

//- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
//
//{
//
//    //一个页面没有被完全加载之前收到下一个请求，此时迅速会出现此error,error=-999
//
//    //此时可能已经加载完成，则忽略此error，继续进行加载。
//
//    //http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
//
//    if([error code] == NSURLErrorCancelled)
//
//    {
//
//        return;
//
//    }
//
//}

@end
